<template>
  <div :id="chartName" style="width: 600px; height: 400px;" :key="chartName" v-for="chartName of chartNames">
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { createWebSocket } from '../../requests'
import * as echarts from "echarts"
import { nextTick } from 'vue';
import ChartConfig from "./ChartConfig.vue"
// interface 
const chartOptions: { [key: string]: echarts.EChartsOption } = {}
const charts: { [key: string]: echarts.ECharts } = {}
const chartNames = ref<string[]>([])

onMounted(() => {
  createWebSocket("ws://localhost:5000/dynamic_chart", (data: { type: string, data: { [key: string]: echarts.EChartsOption } }) => {
    if (data.type == "initial") {
      for (const [key, value] of Object.entries(data.data)) {
        chartOptions[key] = value
        chartNames.value.push(key)
        nextTick(() => {
          const chart = echarts.init(document.getElementById(key))
          charts[key] = chart
        })

      }
    } else if (data.type == "update") {
      for (const [key, chartOptionPatch] of Object.entries(data.data)) {
        const chartOptionToUpdate = chartOptions[key]
        if (chartOptionToUpdate == null || chartOptionToUpdate.series == null) {
          console.error("data of chart options are null", chartOptionPatch)
          continue
        }
        for (const seriesIndex in (chartOptionPatch.series as any[])) {
          const series = (chartOptionToUpdate.series as echarts.SeriesOption[])[seriesIndex];
          (series.data as any[]).push((chartOptionPatch.series as echarts.SeriesOption[])[seriesIndex])
        }
        charts[key].setOption(chartOptionToUpdate)
      }
    }
  })
})


</script>
<style lang="css">
.el-table .el-scrollbar__view {
  width: 100%;
}

::v-deep(.el-table__row:not([class*='el-table__row--level-'])) {
  td:first-child {
    padding-left: 24px;
  }
}
</style>